import {
	RSAencrypt
} from './jsencrypt.js';


import uuid from 'uuid/v1';
// global.js

function init() {
	let url=uni.getStorageSync('wsuri');
	this.websock = new WebSocket(url);
	// 监听socket连接
	this.websock.onopen = function() {
		console.log("socket连接成功")
		localStorage.setItem("readyState", "连接成功");
	}
	// 监听socket错误信息
	this.websock.onerror = function() {
		console.log("连接错误")
		localStorage.setItem("readyState", "连接断开");
	}
	// 监听socket消息
	this.websock.onmessage = function(msg) {
		let res = JSON.parse(msg.data);
		console.log(res);
	}
	//监听socket断开
	this.websock.onclose = function() {
		console.log("socket已经关闭")
		localStorage.setItem("readyState", "连接断开");
		//this.reconnect();
		setTimeout(init, 1000);
	}
}



function setWsUrl(wsuri) {
	uni.setStorageSync('wsuri',wsuri);
	this.init();
}
export default {
	setWsUrl,
	init,
	websock: {},
	webSocketSend(data) {
		if (this.websock.readyState === 1) {
			console.log("发送连接事件：" + JSON.stringify(data));
			this.websock.send(RSAencrypt(JSON.stringify(data)));
		}
	}
}
